#include <iostream>
#include <vector>
#include <thread>
#include <chrono>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>

using namespace std;

void client_thread(int id) {
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    
    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(8080);
    server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    
    if (connect(sock, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
        cout << "Thread " << id << ": 连接失败" << endl;
        return;
    }
    
    char buffer[1024] = {0};
    // 接收服务器的欢迎消息
    recv(sock, buffer, sizeof(buffer), 0);
    
    // 发送100次消息测试
    for(int i = 0; i < 100; i++) {
        string msg = "Test from client " + to_string(id) + " msg " + to_string(i);
        send(sock, msg.c_str(), msg.length(), 0);
        
        memset(buffer, 0, sizeof(buffer));
        recv(sock, buffer, sizeof(buffer), 0);
    }
    
    close(sock);
    cout << "Thread " << id << " 完成测试" << endl;
}

int main() {
    int num_clients = 100; // 同时创建10个客户端
    vector<thread> threads;
    
    auto start = chrono::high_resolution_clock::now();
    
    // 创建多个客户端线程
    for(int i = 0; i < num_clients; i++) {
        threads.emplace_back(client_thread, i);
        this_thread::sleep_for(chrono::milliseconds(100)); // 间隔100ms创建新客户端
    }
    
    // 等待所有线程完成
    for(auto& t : threads) {
        t.join();
    }
    
    auto end = chrono::high_resolution_clock::now();
    auto duration = chrono::duration_cast<chrono::milliseconds>(end - start);
    
    cout << "测试完成！" << endl;
    cout << "总时间: " << duration.count() << "ms" << endl;
    cout << "平均每个客户端时间: " << duration.count() / num_clients << "ms" << endl;
    
    return 0;
}